<?php

class Page{
	// 每页显示个数
	protected $number;
	// 当前页
	protected $page;
	// 一共多少条数据
	protected $totalCount;
	// 一共多少页
	protected $totalPage;
	// url
	protected $url;

	public function __construct($totalCount, $number)
	{
		$this->number = $number;
		$this->totalCount = $totalCount;
		// 获取一共多少页
		$this->totalPage = $this->getTotalPage();
		// 获取当前页
		$this->page = $this->getPage();
		// 组装url
		$this->url = $this->getUrl();
	}

	// 获取所有url
	public function allUrl()
	{
		$urlArr = [];
		$urlArr['first'] = $this->first();
		$urlArr['prev'] = $this->prev();
		$urlArr['next'] = $this->next();
		$urlArr['end'] = $this->end();
		$urlArr['limit'] = $this->limit();

		return $urlArr;
	}

	protected function getUrl()
	{
		$uri = $_SERVER['REQUEST_URI'];
		// 协议
		$scheme = $_SERVER['REQUEST_SCHEME'];
		// 主机名
		$name = $_SERVER['SERVER_NAME'];
		// 端口号
		$port = $_SERVER['SERVER_PORT'];
		// 文件路径
		$path = parse_url($uri)['path'];
		$param = $_GET;
		if(!empty($_GET)){
			unset($param['page']);
		}
		$newParam = http_build_query($param);
		if($newParam != ""){
			$path = $path."?".$newParam;
		}

		return $path;
		
	}

	protected function getTotalPage()
	{
		return ceil($this->totalCount / $this->number);
	}

	protected function getPage()
	{
		if(empty($_GET['page'])) {
			$newpage = 1;
		}else if($_GET['page'] < 1){
			$newpage = 1;
		}else if ($_GET['page'] > $this->totalPage) {
			$newpage = $this->totalPage;
		}else{
			$newpage = $_GET['page'];
		}
		return $newpage;
	}

	public function setUrl($str)
	{
		if(strstr($this->url, "?")){
			$url = $this->url."&".$str;
		}else{
			$url = $this->url."?".$str;
		}
		return $url;
	}

	// 首页
	public function first()
	{
		return $this->setUrl("page=1");
	}

	// 上一页
	public function prev()
	{
		if($this->page - 1 < 1){
			$page = 1;
		}else{
			$page = $this->page - 1;
		}
		return $this->setUrl("page=".$page);
	}

	// 下一页
	public function next()
	{
		if($this->page + 1 > $this->totalPage){
			$page = $this->totalPage;
		}else{
			$page = $this->page + 1;
		}
		return $this->setUrl("page=".$page);
	}

	// 最后一页
	public function end()
	{
		return $this->setUrl("page=".$this->totalPage);
	}

	protected function limit()
	{
		return $this->page * $this->number.",".($this->page + 1) * $this->number;
	}
}
